
package lohmar.ashar.android.util;

import android.util.AndroidException;
import android.util.AndroidRuntimeException;

import java.lang.reflect.Method;

/**
 * @author Mihai HARAS (Lohmar ASHAR) 2011
 */
public class ReflectionMethodCaller {
    public static Object callGetter(Object x, String methodName) throws Exception {
        Method m = getMethod(x, methodName);
        boolean b = m.isAccessible();
        m.setAccessible(true);
        Object val = null;
        try {
            val = m.invoke(x, new Object[] {});
        } catch (Exception e) {
            throw new AndroidException(e);
        } finally {
            m.setAccessible(b);
        }
        return val;
    }

    public static void callSetter(Object x, String methodName, Object... value) throws Exception {
        Method m = getMethod(x, methodName);
        boolean b = m.isAccessible();
        m.setAccessible(true);
        try {
            m.invoke(x, value);
        } catch (Exception e) {
            throw new AndroidException(e);
        } finally {
            m.setAccessible(b);
        }
    }

    private static Method getMethod(Object x, String methodName) {
        Class<?> c = x.getClass();
        Method[] theMethods = c.getMethods();
        for (int i = 0; i < theMethods.length; i++) {
            String methodString = theMethods[i].getName();
            if (methodString.trim().equalsIgnoreCase(methodName.trim())) return theMethods[i];
        }
        // TODO add explaining message
        throw new AndroidRuntimeException();
    }
}
